<template>
  <div class="bridge-flow-container">
    <div class="flow-layout">
      <!-- 左侧流程图 -->
      <div class="flow-diagram">
        <div class="flow-nodes">
          <div 
            v-for="(node, index) in flowNodes" 
            :key="index"
            :class="[
              'flow-node', 
              { 
                active: index <= currentNode.realIndex, 
                current: index === currentNode.realIndex,
                viewing: index === currentNode.viewIndex && index !== currentNode.realIndex 
              }
            ]"
          >
            <el-tooltip
              :content="`${node.label}${index < currentNode.realIndex ? '（已完成）' : index === currentNode.realIndex ? '（进行中）' : ''}`"
              placement="right"
              :effect="index < currentNode.realIndex ? 'light' : index === currentNode.realIndex ? 'success' : 'dark'"
              :show-after="100"
              :hide-after="0"
            >
              <div class="node-circle" 
                   @click="handleNodeClick(index)" 
                   :class="{'clickable': index <= currentNode.realIndex}"
                   :title="`点击查看${node.label}节点`">
                <el-icon :size="24" :color="index <= currentNode.realIndex ? '#ffffff' : '#909399'">
                  <component :is="node.icon" />
                </el-icon>
              </div>
            </el-tooltip>
            <div v-if="index < flowNodes.length - 1" class="node-connector">
              <el-icon v-if="index < currentNode.realIndex" class="connector-icon">
                <ArrowDown />
              </el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div class="flow-content">
        <!-- 顶部标题 -->
        <div class="content-header">
          <div class="header-left">
            <h2 class="page-title">应急工作记录 <span class="event-id"></span></h2>
          </div>
          <div class="event-info">
            <el-tag :type="getEventTypeTag(currentEvent?.eventType)">
              事件编号：{{ currentEvent?.id }}
            </el-tag>
          </div>
        </div>

        <!-- 动态组件区域 -->
        <component 
          :is="currentComponent"
          :event-data="currentEvent"
          @next-step="goToNextNode"
          @start-process="handleStartProcess"
          @end-process="handleEndProcess"
          @complete-summary="handleCompleteSummary"
        />
      </div>
    </div>

    <!-- 开始处理对话框 -->
    <el-dialog
      v-model="startDialogVisible"
      title="开始现场处置"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="dialog-content">
        <div class="dialog-icon">
          <el-icon :size="48" color="#409EFF"><Warning /></el-icon>
        </div>
        <p class="dialog-title">是否立即开始处理该事件？</p>
        <el-form
          ref="startFormRef"
          :model="startForm"
          :rules="startRules"
          label-width="100px"
        >
          <el-form-item label="处理说明" prop="description">
            <el-input
              v-model="startForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入处理说明"
            />
          </el-form-item>
          <el-form-item label="处理人员" prop="handler">
            <el-select v-model="startForm.handler" placeholder="请选择处理人员">
              <el-option
                v-for="item in handlerOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelStart">取 消</el-button>
          <el-button type="primary" @click="confirmStart">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 结束处理对话框 -->
    <el-dialog
      v-model="endDialogVisible"
      title="应急终止"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="dialog-content">
        <div class="dialog-icon">
          <el-icon :size="48" color="#67C23A"><CircleCheck /></el-icon>
        </div>
        <p class="dialog-title">该事件处理已完成，是否进行应急终止？</p>
        <el-form
          ref="endFormRef"
          :model="endForm"
          :rules="endRules"
          label-width="100px"
        >
          <el-form-item label="处理总结" prop="summary">
            <el-input
              v-model="endForm.summary"
              type="textarea"
              :rows="4"
              placeholder="请输入处理总结"
            />
          </el-form-item>
          <el-form-item label="处理结果" prop="result">
            <el-radio-group v-model="endForm.result">
              <el-radio label="success">处理成功</el-radio>
              <el-radio label="warning">部分完成</el-radio>
              <el-radio label="danger">处理失败</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelEnd">取 消</el-button>
          <el-button type="primary" @click="confirmEnd">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import type { Component } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { useRoute, useRouter } from 'vue-router';
import { getEmergencyEventById, updateEmergencyEvent } from '@/api/bridge/command/event';
import {
  Operation,
  CircleCheck,
  Document,
  DataAnalysis,
  Warning,
  ArrowDown,
  VideoPlay,
  Document as DocumentIcon,
  Bell,
  Finished,
  Tools,
  Collection,
  Select,
  Switch,
  Back
} from '@element-plus/icons-vue';

// 导入子组件
import PlanSelectNode from './components/flow/PlanSelectNode.vue';
import EmergencyNoticeNode from './components/flow/EmergencyNoticeNode.vue';
import FieldProcessingNode from './components/flow/FieldProcessingNode.vue';
import EmergencyEndNode from './components/flow/EmergencyEndNode.vue';
import PostProcessingNode from './components/flow/PostProcessingNode.vue';
import EmergencySummaryNode from './components/flow/EmergencySummaryNode.vue';

interface FlowNode {
  label: string;
  status: string;
  icon: Component;
  component: string;
}

// 流程节点定义
const flowNodes: FlowNode[] = [
  { label: '预案选择', status: 'plan-select', icon: Select, component: 'PlanSelectNode' },
  { label: '险情同步', status: 'emergency-notice', icon: Bell, component: 'EmergencyNoticeNode' },
  { label: '现场处置', status: 'field-processing', icon: Operation, component: 'FieldProcessingNode' },
  { label: '应急终止', status: 'emergency-end', icon: Finished, component: 'EmergencyEndNode' },
  { label: '后期处置', status: 'post-processing', icon: Tools, component: 'PostProcessingNode' },
  { label: '应急总结', status: 'emergency-summary', icon: Collection, component: 'EmergencySummaryNode' }
];

// 组件映射
const componentMap: Record<string, any> = {
  PlanSelectNode,
  EmergencyNoticeNode,
  FieldProcessingNode,
  EmergencyEndNode,
  PostProcessingNode,
  EmergencySummaryNode
};

// 路由相关
const route = useRoute();
const router = useRouter();

// 当前节点
const currentNode = ref({
  realIndex: 0, // 实际进度索引
  viewIndex: 0  // 当前查看的节点索引
});

// 当前组件
const currentComponent = computed(() => {
  return componentMap[flowNodes[currentNode.value.viewIndex].component];
});

// 当前事件
const currentEvent = ref({
  id: '',
  eventId: '',
  eventType: 1,
  priority: 3,
  location: '',
  description: '',
  status: 1,
  flowStatus: 1,
  createTime: '',
  handler: ''
});

// 处理人员选项
const handlerOptions = [
  { value: 'user1', label: '张三' },
  { value: 'user2', label: '李四' },
  { value: 'user3', label: '王五' }
];

// 开始对话框相关
const startDialogVisible = ref(false);
const startFormRef = ref();
const startForm = ref({
  description: '',
  handler: ''
});

const startRules = {
  description: [
    { required: true, message: '请输入处理说明', trigger: 'blur' },
    { min: 10, message: '处理说明不能少于10个字符', trigger: 'blur' }
  ],
  handler: [
    { required: true, message: '请选择处理人员', trigger: 'change' }
  ]
};

// 结束对话框相关
const endDialogVisible = ref(false);
const endFormRef = ref();
const endForm = ref({
  summary: '',
  result: 'success'
});

const endRules = {
  summary: [
    { required: true, message: '请输入处理总结', trigger: 'blur' },
    { min: 10, message: '处理总结不能少于10个字符', trigger: 'blur' }
  ],
  result: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ]
};

// 获取事件类型名称
const getEventTypeName = (type: number) => {
  const types = {
    1: '自然灾害',
    2: '事故灾难',
    3: '公共卫生',
    4: '社会安全'
  };
  return types[type] || '-';
};

// 获取事件类型标签样式
const getEventTypeTag = (type: number) => {
  const tags = {
    1: 'danger',
    2: 'warning',
    3: 'success',
    4: 'info'
  };
  return tags[type] || '';
};

// 获取优先级名称
const getPriorityName = (priority: number) => {
  const priorities = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急'
  };
  return priorities[priority] || '-';
};

// 获取优先级标签样式
const getPriorityTag = (priority: number) => {
  const tags = {
    1: 'info',
    2: 'warning',
    3: 'danger',
    4: 'danger'
  };
  return tags[priority] || '';
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取事件详情
const fetchEventDetail = async (eventId) => {
  try {
    if (!eventId) {
      ElMessage.warning('事件ID不存在，请返回事件列表');
      return;
    }

    const res = await getEmergencyEventById(eventId);
    if (res.code === 200) {
      currentEvent.value = res.data;
      
      // 根据flowStatus更新当前节点
      if (currentEvent.value.flowStatus === 7) {
        // 处理完成状态，最后一个节点显示为活动状态
        const lastNodeIndex = flowNodes.length -1;
        currentNode.value.realIndex = lastNodeIndex+1;
        currentNode.value.viewIndex = lastNodeIndex;
      } else if (currentEvent.value.flowStatus && currentEvent.value.flowStatus >= 1 && currentEvent.value.flowStatus <= 6) {
        const nodeIndex = currentEvent.value.flowStatus - 1;
        currentNode.value.realIndex = nodeIndex;
        currentNode.value.viewIndex = nodeIndex;
      } else {
        currentNode.value.realIndex = 0;
        currentNode.value.viewIndex = 0;
      }
    } else {
      ElMessage.error(res.msg || '获取事件详情失败');
    }
  } catch (error) {
    console.error('获取事件详情失败:', error);
    ElMessage.error('获取事件详情失败');
  }
};

// 更新事件流程状态
const updateEventFlowStatus = async (status) => {
  try {
    const updateData = {
      ...currentEvent.value,
      flowStatus: status
    };
    const res = await updateEmergencyEvent(updateData);
    if (res.code === 200) {
      // 更新成功后重新获取事件详情
      await fetchEventDetail(currentEvent.value.id);
      return true;
    } else {
      ElMessage.error(res.msg || '更新事件状态失败');
      return false;
    }
  } catch (error) {
    console.error('更新事件状态失败:', error);
    ElMessage.error('更新事件状态失败');
    return false;
  }
};

// 进入下一节点
const goToNextNode = async () => {
  if (currentNode.value.realIndex < flowNodes.length - 1) {
    const nextNodeIndex = currentNode.value.realIndex + 1;
    // 更新事件的flowStatus字段为下一个节点的索引+1
    const success = await updateEventFlowStatus(nextNodeIndex + 1);
    if (success) {
      currentNode.value.realIndex = nextNodeIndex;
      currentNode.value.viewIndex = nextNodeIndex;
      ElMessage.success(`进入${flowNodes[nextNodeIndex].label}阶段`);
    }
  }
};

// 开始处理
const handleStartProcess = () => {
  startDialogVisible.value = true;
};

// 取消开始处理
const handleCancelStart = () => {
  ElMessageBox.confirm('确定要取消开始处理吗？', '提示', {
    type: 'warning'
  }).then(() => {
    startDialogVisible.value = false;
  });
};

// 确认开始处理
const confirmStart = async () => {
  if (!startFormRef.value) return;
  await startFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        ElMessage.success('开始处理成功');
        currentNode.value.realIndex = 2; // 进入现场处置节点
        currentNode.value.viewIndex = 2;
        startDialogVisible.value = false;
        // 更新当前事件的处理人
        currentEvent.value.handler = startForm.value.handler;
      } catch (error) {
        console.error('开始处理失败:', error);
        ElMessage.error('开始处理失败');
      }
    }
  });
};

// 结束处理
const handleEndProcess = async () => {
  try {
    // 更新事件的flowStatus字段为4（应急终止阶段）和status字段为3（已处置）
    const updateData = {
      ...currentEvent.value,
      flowStatus: 4, // 表示进入应急终止阶段
      status: 3 // 表示事件已处置
    };
    
    const res = await updateEmergencyEvent(updateData);
    
    if (res.code === 200) {
      ElMessage.success('处置已结束，进入应急终止阶段');
      currentNode.value.realIndex = 3; // 进入应急终止节点
      currentNode.value.viewIndex = 3;
    } else {
      ElMessage.error(res.msg || '更新事件状态失败');
    }
  } catch (error) {
    console.error('结束处理失败:', error);
    ElMessage.error('更新事件状态失败');
  }
};

// 取消结束处理
const handleCancelEnd = () => {
  ElMessageBox.confirm('确定要取消结束处理吗？', '提示', {
    type: 'warning'
  }).then(() => {
    endDialogVisible.value = false;
  });
};

// 确认结束处理
const confirmEnd = async () => {
  if (!endFormRef.value) return;
  await endFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        ElMessage.success('结束处理成功');
        currentNode.value.realIndex = 3; // 进入应急终止节点
        currentNode.value.viewIndex = 3;
        endDialogVisible.value = false;
      } catch (error) {
        console.error('结束处理失败:', error);
        ElMessage.error('结束处理失败');
      }
    }
  });
};

// 完成总结
const handleCompleteSummary = async () => {
  try {
    // 更新事件的status字段为4（已关闭）和flowStatus为7（所有节点已完成）
    const updateData = {
      ...currentEvent.value,
      status: 4, // 事件关闭
      flowStatus: 7 // 所有节点已完成
    };
    
    const res = await updateEmergencyEvent(updateData);
    
    if (res.code === 200) {
      ElMessage.success('总结已完成，事件已关闭');
      // 重新获取事件详情并刷新页面状态
      await fetchEventDetail(currentEvent.value.id);
      // 强制重新渲染组件
      nextTick(() => {
        window.location.reload();
      });
    } else {
      ElMessage.error(res.msg || '更新事件状态失败');
    }
  } catch (error) {
    console.error('完成总结失败:', error);
    ElMessage.error('更新事件状态失败');
  }
};

// 处理节点点击
const handleNodeClick = (index: number) => {
  // 只有当点击的节点不超过当前实际进度节点时才允许查看
  if (index <= currentNode.value.realIndex) {
    // 只切换查看的内容，不改变实际进度
    currentNode.value.viewIndex = index;
    
    if (index !== currentNode.value.realIndex) {
    }
  } else {
    ElMessage.warning('您需要先完成当前步骤');
  }
};

onMounted(() => {
  // 从路由获取事件ID
  const eventId = route.query.eventId;
  if (eventId) {
    fetchEventDetail(eventId);
  } else {
    ElMessage.warning('未提供事件ID，将显示默认流程');
  }
});

// 监听路由变化
watch(
  () => route.query.eventId,
  (newEventId) => {
    if (newEventId) {
      fetchEventDetail(newEventId);
    }
  }
);
</script>

<style scoped lang="scss">
.bridge-flow-container {
  padding: 20px;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  min-height: 100%;
}

.flow-layout {
  display: flex;
  gap: 40px;
  min-height: calc(100vh - 120px);
}

.flow-diagram {
  width: 80px;
  padding: 20px 10px;
  background: var(--el-bg-color-overlay);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  display: flex;
  justify-content: center;
  align-items: center;

  .flow-nodes {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 50px;
  }

  .flow-node {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    padding: 5px 0;

    &.active {
      .node-circle {
        background: var(--el-color-primary);
        color: white;
      }

      .node-connector {
        border-color: var(--el-color-primary);
        color: white;
      }
    }

    &.current {
      .node-circle {
        background: var(--el-color-success);
        color: white;
      }
    }
    
    &.viewing {
      .node-circle {
        background: var(--el-color-warning);
        color: white;
        box-shadow: 0 0 0 4px rgba(230, 162, 60, 0.2);
      }
    }
  }

  .node-circle {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: var(--el-color-info-light-8);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
    cursor: pointer;

    &.clickable {
      cursor: pointer;
      position: relative;
      
      &:after {
        content: '';
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        border: 2px solid transparent;
        top: 0;
        left: 0;
        transition: all 0.3s ease;
      }
      
      &:hover {
        transform: scale(1.1);
        
        &:after {
          border-color: var(--el-color-primary-light-3);
          animation: pulse 1.5s infinite;
        }
      }
    }
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
      opacity: 0.8;
    }
    70% {
      transform: scale(1.1);
      opacity: 0.3;
    }
    100% {
      transform: scale(1);
      opacity: 0.8;
    }
  }

  .node-connector {
    position: absolute;
    top: 48px;
    left: 50%;
    width: 2px;
    height: 85px;
    border-left: 2px dashed var(--el-border-color);
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    justify-content: center;

    .connector-icon {
      position: absolute;
      top: 50%;
      color: var(--el-color-primary);
      transform: translateY(-50%);
    }
  }
}

.flow-content {
  flex: 1;
  background: var(--el-bg-color-overlay);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  padding: 20px;

  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--el-border-color-light);

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .page-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .event-info {
      display: flex;
      align-items: center;
      gap: 16px;

      .event-id {
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }
  }
}

.dialog-content {
  text-align: center;

  .dialog-icon {
    margin-bottom: 20px;
  }

  .dialog-title {
    margin: 0 0 20px;
    font-size: 16px;
    color: var(--el-text-color-primary);
    font-weight: 500;
  }
}

:deep(.el-dialog) {
  border-radius: 8px;
  
  .el-dialog__header {
    margin: 0;
    padding: 20px 24px;
    border-bottom: 1px solid var(--el-border-color-light);
  }
  
  .el-dialog__body {
    padding: 24px;
  }
  
  .el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid var(--el-border-color-light);
  }
}
</style>
